package com.itheima.leyou.search.mq;

import com.itheima.leyou.common.constants.MQConstants;
import com.itheima.leyou.service.SearchService;
import org.springframework.amqp.core.ExchangeTypes;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;



@Component
public class ItemListener {

  @Autowired
  private SearchService searchService;

    /**
     * 接收mq发送的消息
     * 交换机和队列的绑定
     * @param spuId
     */
    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(name = MQConstants.QueueConstants.SEARCH_ITEM_UP, durable = "true"),
            exchange = @Exchange(name = MQConstants.ExchangeConstants.ITEM_EXCHANGE_NAME, type = ExchangeTypes.TOPIC),
            key = MQConstants.RoutingKeyConstants.ITEM_UP_KEY
    ))
    public void listenItemUp(Long spuId){
        if (spuId != null) {
            // 商品上架，我们新增商品到索引库
            searchService.saveGoodsById(spuId);
        }
    }

    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(name = MQConstants.QueueConstants.SEARCH_ITEM_DOWN, durable = "true"),
            exchange = @Exchange(name = MQConstants.ExchangeConstants.ITEM_EXCHANGE_NAME, type = ExchangeTypes.TOPIC),
            key = MQConstants.RoutingKeyConstants.ITEM_DOWN_KEY
    ))
    public void listenItemDown(Long spuId){
        if (spuId != null) {
            // 商品下架，我们删除商品
            searchService.deleteGoodsById(spuId);
        }
    }
}